package com.sxyjhh.service.data_exchange;

import com.sxyjhh.common.DBConfig;
import com.sxyjhh.dbutil.basic.ConstConfig;
import com.sxyjhh.dbutil.basic.DBQueryUtils;
import com.sxyjhh.dbutil.utils.DBInfoUtil;
import com.sxyjhh.dbutil.utils.PageInfo;
import com.sxyjhh.schedule.TaskRunnable;
import com.sxyjhh.service.insert_csafetycertificate.InsertCsafetycertificate_InsertCsafetycertificatePort_Client;
import com.sxyjhh.utils.CommonUtils;
import com.sxyjhh.utils.FtpUtil;
import com.sxyjhh.utils.util.XaUtil;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/6/25.
 */
public class PollingRunnableImage extends TaskRunnable {

    private String tabName;
    private String key;
    private FTPClient ftpClient = new FTPClient();

    private String ip = DBConfig.readPop("output.datasource.ip");
    private String dbName = DBConfig.readPop(" output.datasource.db.name");
    private String userName = DBConfig.readPop("output.datasource.username");
    private String password = DBConfig.readPop("output.datasource.passwordp");
    private String port = DBConfig.readPop("output.datasource.port");
    private String type = DBConfig.readPop("output.datasource.type");
    private String personTabName = DBConfig.readPop("PERSON.SECURITY.CERTIFICATE");

    Map<String,String> dicMap = new HashMap<>();

    public PollingRunnableImage(String tabName, String key) {
        this.taskId = "Image_polling-" + tabName;
        this.tabName = tabName;
        this.key = key;
    }


    @Override
    public synchronized void run() {
        System.out.println("——————————————————————ThreadName————————————————————————");
        System.out.println(Thread.currentThread().getName());
        System.out.println("——————————————————————TaskName————————————————————————");
        System.out.println(taskId);
        System.out.println("——————————————————————possTime————————————————————————");
        System.out.println(CommonUtils.YYYYMMDDHHMMSS.format(new Date()));


        String url = "";
        ConstConfig.DBType dbType = ConstConfig.DBType.valueOf(Integer.valueOf(type));
        if ("3".equals(type)) {
            url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useInformationSchema=true&useSSL=false";
        } else {
            url = DBInfoUtil.getDBUrl(dbType, ip, port, dbName);
        }

        DBQueryUtils dbQueryUtils = new DBQueryUtils(DBInfoUtil.getDBDriverName(dbType),
                url, userName, password, 5);

        try {
            FtpUtil.getInstance().connect(ftpClient, "192.168.2.180", 2121, "yjhh", "a1b2c3d4!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        pushData(tabName, dbQueryUtils);

    }

    //推送数据
    private void pushData(String tableName, DBQueryUtils dbQueryUtils) {

        int outCount = 0;
        try {
            List countList = dbQueryUtils.queryData("select count(1) as cut from " + tableName);
            if (!XaUtil.isEmpty(countList)) {
                JSONObject countJson = JSONObject.fromObject(countList.get(0));
                outCount = (int) countJson.get("cut");
            }

            int num = 1000;
            int batch = (outCount / num) + (outCount % num != 0 ? 1 : 0);

            for (int i = 0; i < batch; i++) {
                PageInfo pageInfo = dbQueryUtils.queryTableDataByPaging(dbName, tableName, i + 1, num, "select * from " + tableName);

                List<Map> resultlist = pageInfo.getResultList();

                for (Map resMap : resultlist) {

                    String path = (String) resMap.get("path");
                    String personId = resMap.get("FLINKID") + "";

                    List data = dbQueryUtils.queryData("select *  from " + personTabName + " where PERSON_SECURITY_CERTIFICATE_ID ='" + personId + "'");
                    JSONObject jsonObject = null;
                    String image = "";
                    if (!XaUtil.isEmpty(data)) {
                        jsonObject = JSONObject.fromObject(data.get(0));
                        image = ftpDownload(path);
                        jsonObject.put("PHOTO", image);
                        jsonObject.put("OPERATION_FLAG", "U");
                    }else{
                        continue;
                    }

                    String pushData = "{'PERSON_SECURITY_CERTIFICATE':" + jsonObject.toString() + "}";
                    System.out.println(pushData);
                    String result = InsertCsafetycertificate_InsertCsafetycertificatePort_Client.push(pushData);
                    System.out.println(result);
                    if (result.contains("200")) {
                        String keyValue = (String) resMap.get(key);
                        deleteData(tableName, key, keyValue, dbQueryUtils);
                    }

                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //删除推送成功的数据
    private boolean deleteData(String tableNmae, String key, String keyValue, DBQueryUtils dbQueryUtils) {
        boolean flag = true;

        StringBuilder sql = new StringBuilder("delete from ");
        sql.append(tableNmae);
        sql.append(" where ");
        sql.append(key);
        sql.append(" = '");
        sql.append(keyValue);
        sql.append("' ");
        System.out.println(sql.toString());
        try {
            flag = dbQueryUtils.execDDLSql(sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    private String ftpDownload(String path) {


        String imgBase64 = "";
        try {
            byte[] imageByte = FtpUtil.getInstance().download(ftpClient, path);
            if (!XaUtil.isEmpty(imageByte)) {
                imgBase64 = Base64.encodeBase64String(imageByte);
                return imgBase64;
            } else {
                return imgBase64;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return imgBase64;
        }
    }

    private void pollingData(Map<String, Object> map, Map<String, Object> resMap, Date date) {

        String sex = map.get("FSEX") + "";
        if (!StringUtils.isBlank(sex)) {
            sex = "男".equals(sex) ? "01" : "女".equals(sex) ? "02" : "";
        }
        resMap.put("PERSON_SECURITY_CERTIFICATE_ID", map.get("FID"));
        resMap.put("PROVICE_CODE", "610000");
        resMap.put("NAME", map.get("FNAME"));
        resMap.put("ID_CARDS_TYPE", !XaUtil.isEmpty(map.get("FIDCARDTYPEID")) ? dicMap.get(map.get("FIDCARDTYPEID")) : "");
        resMap.put("ID_CARDS_NUMBER", map.get("FIDCARD"));
        resMap.put("SEX", sex);
        resMap.put("BIRTHDAY", dateFormat(map.get("FBIRTHDAY")));
        resMap.put("EDULEVEL", !XaUtil.isEmpty(map.get("FDEGREEID")) ? dicMap.get(map.get("FDEGREEID")) : "");
        resMap.put("PHOTO", "");
        resMap.put("PERSON_TYPE", !XaUtil.isEmpty(map.get("FPERSONTYPEID")) ? dicMap.get(map.get("FPERSONTYPEID")) : "");
        resMap.put("COMPANY_NAME", map.get("FBASENAME"));
        resMap.put("COMPANY_CREDIT_CODE", map.get("FJURIDCIALCODE"));
        resMap.put("POST", map.get("FFUNCTION"));
        resMap.put("POSITIONAL_TITLE", "");
        resMap.put("CERTIFICATE_NUMBER", map.get("FCERTINO"));
        resMap.put("CERTIFICATE_START_DATE", dateFormat(map.get("FBEGINTIME")));
        resMap.put("CERTIFICATE_END_DATE", dateFormat(map.get("FENDTIME")));
        resMap.put("CERTIFICATE_AUTHORITY", "陕西省住房和城乡建设厅");
        resMap.put("CERTIFICATE_SEND_DATE", dateFormat(map.get("FAPPTIME")));
        resMap.put("CERTIFICATE_CONTINUE_DATE", "");
        resMap.put("CERTIFICATE_STATE", map.get("FSTATE"));
        resMap.put("ELECTRONIC_CERTIFICATES", "");
        resMap.put("OPERATION_FLAG", map.get("OPERATION_FLAG"));
        resMap.put("CREATEDATE", com.sxyjhh.dbutil.utils.CommonUtils.YYYYMMDD.format(date));
        resMap.put("CERTIFICATE_RECHECK_DATE", "");
        resMap.put("OPERATE_TYPE", "");
    }
    private String dateFormat(Object time) {
        if (XaUtil.isEmpty(time)) {
            return null;
        }
        String dateFormat = time + "";
        return dateFormat.substring(0, 10);
    }

}
